<template>
  <div class="schedule">
    <!--<a-row>
      <a-col>
        <span class="topSelect">
          <a-select v-model="year" style="width: var(--width)">
            <a-select-option
              v-for="(item, index) in yearList"
              :key="index"
              :value="item"
              >{{ item }}</a-select-option
            >
          </a-select>
          <a-select v-model="semester" style="width: var(--width)">
            <a-select-option value="1"> 第一学期 </a-select-option
            ><a-select-option value="2"> 第二学期 </a-select-option>
          </a-select>
          <a-select
            default-value="place"
            style="width: var(--width)"
            @change="styleChange"
          >
            <a-select-option value="place"> 按地点查询 </a-select-option>
            <a-select-option value="people"> 按人员查询 </a-select-option>
          </a-select>
        </span>
        <br />
      </a-col>
    </a-row>-->

    <div class="schedule_treeselect">
      <!-- <div class="treeselect_spaceSelect">
        <a-tree-select
          style="width: 100%"
          :value="campus_value"
          :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
          placeholder="按地点选择"
          allow-clear
          tree-default-expand-all
          @change="onChangerooms"
        >
          <a-tree-select-node
            :selectable="false"
            :key="campus.campus_name"
            :value="`${campus._id}#`"
            :title="campus.campus_name"
            v-for="campus in campusList"
          >
            <a-tree-select-node
              :key="buildings.building_name"
              :value="`${campus._id}:${buildings._id}`"
              :title="buildings.building_name"
              v-for="buildings in campus.buildings"
            >
            </a-tree-select-node>
          </a-tree-select-node>
        </a-tree-select>
      </div> -->
      <div class="schedule_treeselect_select">
        <button class="schedule_treeselect_select_typeBtn" name="typeBtn" @click=selectPlace>
          按地点选择
        </button>
      </div>

      <!-- <div class="treeselect_peopleSelect">
        <a-tree-select
          style="width: 100%"
          :value="people_value"
          :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
          placeholder="按人员选择"
          allow-clear
          tree-default-expand-all
          @change="onTreeChange"
        >
          <a-tree-select-node
            :selectable="false"
            :key="item._id"
            :value="`${item._id}#`"
            :title="item._id"
            v-for="item in peopleTreeList"
          >
            <a-tree-select-node
              :key="title"
              :value="`${item._id}:${title}`"
              :title="title"
              v-for="title in item.title"
            >
            </a-tree-select-node>
          </a-tree-select-node>
        </a-tree-select>
      </div> -->
      <div class="schedule_treeselect_select">
        <button class="schedule_treeselect_select_typeBtn" name="typeBtn" @click=selectPeople>
          按人员选择
        </button>
      </div>
    </div>
  
    <div v-if="this.style === 'place'" class="schedule_selectBox">
      <spin @click="selectCampus(selected.campus)" class="schedule_selectBox_selectText"> {{ this.selected.campus.campus_name }} </spin>
      <spin v-if="this.selected.building.building_name" class="schedule_selectBox_selectIcon"> > </spin>
      <spin @click="selectBuilding(selected.building)" class="schedule_selectBox_selectText"> {{ this.selected.building.building_name }} </spin>
      <spin v-if="this.selected.room" class="schedule_selectBox_selectIcon"> > </spin>
      <spin class="schedule_selectBox_selectText"> {{ this.selected.room }} </spin>
    </div>
    <div v-else class="schedule_selectBox">
      <spin @click="selectItem(selected.item)" class="schedule_selectBox_selectText"> {{ this.selected.item._id }} </spin>
      <spin v-if="this.selected.title" class="schedule_selectBox_selectIcon"> > </spin>
      <spin @click="selectTitle(selected.title)" class="schedule_selectBox_selectText"> {{ this.selected.title }} </spin>
      <spin v-if="this.selected.people" class="schedule_selectBox_selectIcon"> > </spin>
      <spin class="schedule_selectBox_selectText"> {{ this.selected.people }} </spin>
    </div>

    <a-spin v-if="campusVisible" :spinning="Card_spin_status" tip="Loading...">
      <div class="cs-card">
        <div
          class="cs-card-block"
          :key="campus.campus_name"
          v-for="campus in campusList"
          @click="selectCampus(campus)"
        >
          <div class="cs-card-block-name">
            {{ campus.campus_name }}
          </div>
        </div>
      </div>
    </a-spin>
    <a-spin v-if="itemVisible" :spinning="Card_spin_status" tip="Loading...">
      <div class="cs-card">
        <div
          class="cs-card-block"
          :key="item._id"
          v-for="item in peopleTreeList"
          @click="selectItem(item)"
        >
          <div class="cs-card-block-name">
            {{ `${item._id}` }}
          </div>
        </div>
      </div>
    </a-spin>

    <a-spin v-if="buildingVisible" :spinning="Card_spin_status" tip="Loading...">
      <div class="cs-card">
        <div
          class="cs-card-block"
          :key="building.buiding_name"
          v-for="building in selectList.buildingList"
          @click="selectBuilding(building)"
        >
          <div class="cs-card-block-name">
            {{ building.building_name }}
          </div>
        </div>
      </div>
    </a-spin>
    <a-spin v-if="titleVisible" :spinning="Card_spin_status" tip="Loading...">
      <div class="cs-card">
        <div
          class="cs-card-block"
          :key="title"
          v-for="title in selectList.titleList"
          @click="selectTitle(title)"
        >
          <div class="cs-card-block-name">
            {{ title }}
          </div>
        </div>
      </div>
    </a-spin>

    <a-spin v-if="roomVisible | peopleVisible" :spinning="Card_spin_status" tip="Loading...">
      <div class="cs-card">
        <div
          class="cs-card-block"
          :key="item.cardData"
          :value="`${item.cardData}`"
          v-for="item in cardData"
          @click="changeCard(item.cardData, item.cardShow)"
        >
          <div class="cs-card-block-name">
            {{ item.cardShow }}
          </div>
        </div>
      </div>
    </a-spin>
    <!-- <a-spin v-if="peopleVisible" :spinning="Card_spin_status" tip="Loading...">
      <div class="cs-card">
        <div
          class="cs-card-block"
          :key="item.cardData"
          :value="`${item.cardData}`"
          v-for="item in cardData"
          @click="changeCard(item.cardData, item.cardShow)"
        >
          <div class="cs-card-block-name">
            {{ item.cardShow }}
          </div>
        </div>
      </div>
    </a-spin> -->
  </div>
</template>

<script>
import axiosInstance from "@/utils/axios";
import moment from "moment";
import { mapState } from "vuex";
export default {
  data() {
    return {
      Card_spin_status: false,
      // 选择
      year: moment().year() + "-" + moment().add({ years: 1 }).year(),
      semester: "1",
      style: "place",
      selectList: {
        buildingList:[],
        titleList:[],
      },
      selected: {
        campus: {},
        building: {},
        room: null,
        item: null,
        title: {},
        people: null,
      },
      campusVisible: false,
      buildingVisible: false,
      roomVisible: false,
      itemVisible: false,
      titleVisible: false,
      peopleVisible: false,
      campusList: [],
      peopleTreeList: [],
      // 卡片
      cardData: [],
      courseTabledata: [],
      // 缓存信息
      building_name: "",
      // 课表色
      courseColors: [
        "linear-gradient(120deg, #84fab0 0%, #8fd3f4 100%)",
        "linear-gradient(120deg, #a1c4fd 0%, #c2e9fb 100%)",
        "linear-gradient(120deg, #d4fc79 0%, #96e6a1 100%)",
        "linear-gradient(to top, #fbc2eb 0%, #a6c1ee 100%)",
        "linear-gradient(to top, #fdcbf1 0%, #fdcbf1 1%, #e6dee9 100%)",
        "linear-gradient(to right, #ff8177 0%, #ff867a 0%, #ff8c7f 21%, #f99185 52%, #cf556c 78%, #b12a5b 100%)",
        "linear-gradient(to top, #ff9a9e 0%, #fecfef 99%, #fecfef 100%)",
        "linear-gradient(to right, #ffecd2 0%, #fcb69f 100%)",
        "linear-gradient(to top, #fad0c4 0%, #ffd1ff 100%)",
        "linear-gradient(to top, #a18cd1 0%, #fbc2eb 100%)",
        "linear-gradient(45deg, #ff9a9e 0%, #fad0c4 99%, #fad0c4 100%)",
      ],
      courseIndex: 0,
    };
  },
  computed: {
    yearList() {
      let year = moment().year();
      let lastyear = `${year - 1}-${year}`;
      let nextyear = `${year}-${year + 1}`;
      return [lastyear, nextyear];
    },
    ...mapState({
      uid: (state) => state.public.uid,
      Tree_spin_status: (state) => state.admin.Tree_spin_status,
      spin_status: (state) => state.admin.spin_status,
      oid: (state) => state.public.oid,
      orgName: (state) => state.public.orgName,
      school_year: (state) => state.public.school_year,
    }),
  },
  mounted() {
    this.getSpaceTree();
    this.getTreeList();
    this.getCourse();
    this.$store.dispatch("public/getCurrentSchoolYear", this.orgName);
  },

  methods: {
    async getCourse() {
      let date = new Date();
      let year = "";
      // let year = date.getFullYear();
      //  + '-' + Number(date.getFullYear() + 1);
      // let semester = date.getMonth() < 3 || date.getMonth() > 9 ? 1 : 2;
      let semester = -1;

      if (date.getMonth() < 3) {
        year = date.getFullYear() - 1 + "-" + date.getFullYear();
        semester = 1;
      } else if (date.getMonth() > 9) {
        year = date.getFullYear() + "-" + (date.getFullYear() + 1);
        semester = 1;
      } else {
        year = date.getFullYear() - 1 + "-" + date.getFullYear();
        semester = 2;
      }

      this.day = date.getDay();
      let timeData = {
        year: year,
        semester: semester,
      };
      (this.year = timeData.year), (this.semester = timeData.semester);
    },
    // 地点树
    async getSpaceTree() {
      let queryString = "";
      const url = "/pc/v1/campus" + queryString;
      try {
        this.$store.dispatch("admin/change_Tree_spin_status", true);
        const { data } = await axiosInstance.get(url);
        this.$store.dispatch("admin/change_Tree_spin_status", false);
        this.campusList = data.data.campus;
        // console.log("----cam-----")
        // console.log(this.campusList)
      } catch (err) {
        console.log(err);
      }
    },
    // 人员树
    async getTreeList() {
      try {
        // console.log(this.orgName);
        const url =
          "/pc/v1/users/getUsersBySubOrgAndSortByTitle?org_name=" +
          this.orgName;
        this.$store.dispatch("admin/change_Tree_spin_status", true);
        const { data } = await axiosInstance(url);
        this.$store.dispatch("admin/change_Tree_spin_status", false);
        // console.log("---this.peopleTreeList---");
        // console.log(this.peopleTreeList);
        // console.log(data.result);
        data.result.map((item) => {
          let middle = item.title;
          // console.log(middle)
          // item.title = middle.filter((temp) => {
          //   // console.log(temp)
          //   temp == "学生";
          // });
          let test = [];
          for (let i = 0; i < middle.length; i++) {
            if (middle[i] != "学生") test.push(middle[i]);
          }
          item.title = test;
        });
        // console.log(data.result)
        this.peopleTreeList = data.result;
      } catch (err) {
        console.log(err);
      }
    },
    async onTreeChange(value, label) {
      this.style = "people";
      let payload = {};
      let dataArray = value.split(":");
      let secString = "";
      switch (dataArray[1]) {
        case "教授":
          secString = "professor";
          break;
        case "副教授":
          secString = "vice-professor";
          break;
        case "讲师":
          secString = "lecturer";
          break;
        // case "学生":
        //   secString = "student";
        // break;
        default:
          break;
      }
      payload = {
        subOrg_name: dataArray[0],
        title: secString,
      };
      this.getPeopleFromCondition(payload);
    },
    async getPeopleFromCondition(payload) {
      // console.log(payload);
      const url =
        "/pc/v1/users?subOrg_name=" +
        payload.subOrg_name +
        "&title=" +
        payload.title +
        "&org_name=" +
        this.orgName;
      try {
        this.$store.dispatch("admin/change_spin_status", true);
        const { data } = await axiosInstance.get(url);
        this.$store.dispatch("admin/change_spin_status", false);
        // console.log(data.users);
        this.cardData = [];
        data.users.map((item) => {
          let temp = {
            cardShow: item.name,
            cardData: item._id,
          };
          this.cardData.push(temp);
        });
        // console.log("---card-----");
        // console.log(this.cardData);
      } catch (err) {
        console.log(err);
      }
    },
    selectPlace() {
      let typeAll = document.getElementsByName("typeBtn");
      typeAll[0].className = "schedule_treeselect_select_selectedBtn";
      typeAll[1].className = "schedule_treeselect_select_typeBtn";
      this.style = "place";
      this.campusVisible = true;
      this.buildingVisible = false;
      this.roomVisible = false;
      this.itemVisible = false;
      this.titleVisible = false;
      this.peopleVisible = false;
      this.selected = {
        campus: {},
        building: {},
        room: null,
        item: {},
        title: null,
        people: null,
      };
    },
    selectCampus(value) {
      this.selected.building = {},
      this.selected.room = null;
      this.cardData = [],
      this.selected.campus = value;
      for(let i = 0; i < this.campusList.length; i++) {
        if(this.campusList[i].campus_name == value.campus_name) {
          this.selectList.buildingList = this.campusList[i].buildings;
        }
      }
      this.campusVisible = false;
      this.buildingVisible = true;
    },
    selectBuilding(value) {
      this.selected.room = null;
      this.cardData = [],
      this.selected.building = value;
      let selectValue = this.selected.campus._id + ":" + this.selected.building._id;
      this.buildingVisible = false;
      this.roomVisible = true;
      this.onChangerooms(selectValue,[value.building_name]);
    },
    selectPeople() {
      let typeAll = document.getElementsByName("typeBtn");
      typeAll[0].className = "schedule_treeselect_select_typeBtn";
      typeAll[1].className = "schedule_treeselect_select_selectedBtn";
      this.style = "people";
      this.itemVisible = true;
      this.titleVisible = false;
      this.peopleVisible = false;
      this.campusVisible = false;
      this.buildingVisible = false;
      this.roomVisible = false;
      this.selected = {
        campus: {},
        building: {},
        room: null,
        item: {},
        title: null,
        people: null,
      };
    },
    selectItem(item) {
      this.selected.title = null,
      this.selected.people = null;
      this.cardData = [],
      this.selected.item = item;
      this.selectList.titleList = item.title;
      this.itemVisible = false;
      this.titleVisible = true;

    },
    selectTitle(title) {
      this.selected.people = null;
      this.cardData = [],
      this.selected.title = title;
      let selectValue = this.selected.item._id + ":" + this.selected.title;
      this.titleVisible = false;
      this.peopleVisible = true;
      this.onTreeChange(selectValue,[title]);
    },
    styleChange(value) {
      // console.log(value)
      this.style = value;
      // console.log(`selected ${value}`);
    },
    async onChangerooms(value, label) {
      this.style = "place";
      this.flag = value;
      let payload = {};
      let dataArray = this.flag.split(":");
      this.people_value = null;
      for(let i = 0; i < this.campusList.length; i++) {
        if(dataArray[0] == this.campusList[i]._id) {
          for(let j = 0; j < this.campusList[i].buildings.length; j++) {
            if(dataArray[1] == this.campusList[i].buildings[j]._id) {
              this.campus_value = this.campusList[i].campus_name + "/" + this.campusList[i].buildings[j].building_name;
            }
          }
        }
      }
      // console.log("---dataArray---")
      // console.log(label)
      this.building_name = label[0];
      this.getRoomsFromCondition(dataArray[1]);
    },
    async getRoomsFromCondition(building_id) {
      const url =
        "/pc/v1/rooms/getRoomByBuilding?building_id=" +
        building_id +
        "&year=" +
        this.year +
        "&semester=" +
        this.semester;
      try {
        // this.$store.dispatch("admin/change_spin_status", true);
        this.Card_spin_status = true;
        const { data } = await axiosInstance.get(url);
        // this.$store.dispatch("admin/change_spin_status", false);
        this.Card_spin_status = false;
        // console.log("---data---")
        // console.log(data)
        // console.log(data.rooms.rooms);
        this.cardData = [];
        data.rooms.rooms.map((item) => {
          let temp = {
            cardShow: item.room_number,
            cardData: item._id,
          };
          this.cardData.push(temp);
        });
        // console.log("---card-----");
        // console.log(this.cardData);
        // this.roomList = data.data.rooms;
      } catch (err) {
        console.log(err);
      }
    },
    // 卡片
    changeCard(record, label) {
      this.cardData = [];
      if (this.style === "place") {
        this.selected.room = label;
        let url =
          "/pc/v1/timetables/getTimeTableFromRoomID?room_id=" +
          record +
          "&semester=" +
          this.semester +
          "&year=" +
          this.year;
        this.getTimeTableFromRoomID(url, label);
      } else {
        this.selected.people = label;
        // console.log("---record---");
        // console.log(queryString);
        let url = "/pc/v1/timetables/getTimeTableFromTeacherID";
        let queryString = {
          teacher_id: record,
          semester: this.semester,
          year: this.year,
        };
        // console.log(queryString);
        this.$store.dispatch("admin/change_spin_status", true);
        this.getTimeTableFromRoomID(url, queryString);
        this.$store.dispatch("admin/change_spin_status", false);
      }
    },
    async getTimeTableFromRoomID(url, label) {
      // console.log(this.style);
      try {
        let newCourseTabledata = [];
        if (this.style === "place") {
          this.$store.dispatch("admin/change_spin_status", true);
          const { data } = await axiosInstance.get(url);
          this.$store.dispatch("admin/change_spin_status", false);
          // console.log(data.result);
          console.log(
            "🚀 ~ file: ScheduleInfo.vue ~ line 363 ~ getTimeTableFromRoomID ~ data.result",
            data.result
          );

          data.result.forEach((item, index) => {
            // 给每个课程一个课程编号
            this.courseIndex++;
            // 处理单双周
            let week = "全周";
            if (item.odd_or_even === 1) week = "单周";
            else if (item.odd_or_even === 2) week = "双周";
            // 处理周几的课
            let weekTime;
            switch (item.date) {
              case "Mon":
                weekTime = 1;
                break;
              case "Tue":
                weekTime = 2;
                break;
              case "Wed":
                weekTime = 3;
                break;
              case "Thu":
                weekTime = 4;
                break;
              case "Fri":
                weekTime = 5;
                break;
              case "Sat":
                weekTime = 6;
                break;
              case "Sun":
                weekTime = 7;
                break;
              default:
                break;
            }
            // 课程节数排序
            item.order = item.order.sort();
            // 处理课程节数
            var courseIndex = 0;
            var courseNodes = [];
            for (var i = 0; i < item.order.length; i++) {
              if (Number(item.order[i]) + 1 != Number(item.order[i + 1])) {
                var mini = item.order.slice(courseIndex, i + 1);
                mini[mini.length - 1] = Number(mini[mini.length - 1]) + 1;
                courseNodes.push(mini);
                courseIndex = i + 1;
              }
            }
            courseNodes.forEach((courseNode) => {
              newCourseTabledata.push({
                show: {
                  course_name: item.course_name,
                  week: week,
                  building_name: this.building_name,
                  room_name: label,
                  styleColor: this.courseColors[index],
                  courseIndex: this.courseIndex,
                  colStart: weekTime,
                  colEnd: ++weekTime,
                  rowStart: Number(courseNode[0]),
                  rowEnd: courseNode[courseNode.length - 1],
                  teacherName: item.teacher_name,
                },
                _id: item._id,
                match: {
                  semester: this.semester,
                  year: this.year,
                },
              });
            });
          });
          console.log(
            "🚀 ~ file: ScheduleInfo.vue ~ line 371 ~ getTimeTableFromRoomID ~ newCourseTabledata",
            newCourseTabledata
          );
        } else {
          this.$store.dispatch("admin/change_spin_status", true);
          const { data } = await axiosInstance.post(url, label);
          console.log(
            "🚀 ~ file: ScheduleInfo.vue ~ line 460 ~ getTimeTableFromRoomID ~ data",
            data
          );
          this.$store.dispatch("admin/change_spin_status", false);

          let index = 0;
          data.result.forEach((item) => {
            let middle = item.curriculum.forEach((temp) => {
              let week = "全周";
              if (temp.odd_or_even === 1) week = "单周";
              else if (temp.odd_or_even === 2) week = "双周";
              // 处理周几的课
              let weekTime;
              switch (temp.date) {
                case "Mon":
                  weekTime = 1;
                  break;
                case "Tue":
                  weekTime = 2;
                  break;
                case "Wed":
                  weekTime = 3;
                  break;
                case "Thu":
                  weekTime = 4;
                  break;
                case "Fri":
                  weekTime = 5;
                  break;
                case "Sat":
                  weekTime = 6;
                  break;
                case "Sun":
                  weekTime = 7;
                  break;
                default:
                  break;
              }
              // 课程节数排序
              temp.order = temp.order.sort();
              // 处理课程节数
              var courseIndex = 0;
              var courseNodes = [];
              for (var i = 0; i < temp.order.length; i++) {
                if (Number(temp.order[i]) + 1 != Number(temp.order[i + 1])) {
                  var mini = temp.order.slice(courseIndex, i + 1);
                  mini[mini.length - 1] = Number(mini[mini.length - 1]) + 1;
                  courseNodes.push(mini);
                  courseIndex = i + 1;
                }
              }
              courseNodes.forEach((courseNode) => {
                newCourseTabledata.push({
                  show: {
                    course_name: item.course_id.name,
                    week: week,
                    building_name: item.teacher_id.name,
                    room_name: temp.room_id.room_number,
                    styleColor: this.courseColors[index],
                    courseIndex: this.courseIndex,
                    colStart: weekTime,
                    colEnd: ++weekTime,
                    rowStart: Number(courseNode[0]),
                    rowEnd: courseNode[courseNode.length - 1],
                  },
                  _id: item._id,
                  match: {
                    semester: this.semester,
                    year: this.year,
                  },
                });
                index++;
              });
              // return {
              //   show: {
              //     course_name: item.course_id.name,
              //     week: week,
              //     building_name: item.teacher_id.name,
              //     room_name: "",
              //   },
              //   _id: item._id,
              //   match: {
              //     semester: this.semester,
              //     year: this.year,
              //     date: temp.date,
              //     order: temp.order,
              //   },
              // };
            });
            return middle;
          });
          // let CourseTabledata = [];
          // for (let i = 0; i < newCourseTabledata.length; i++) {
          //   for (let j = 0; j < newCourseTabledata[i].length; j++) {
          //     CourseTabledata.push(newCourseTabledata[i][j]);
          //     // console.log(newCourseTabledata[i][j])
          //   }
          // }
          // // console.log(newCourseTabledata.length);
          // // console.log(newCourseTabledata[i].length);
          // // console.log(CourseTabledata);
          // newCourseTabledata = CourseTabledata;
        }
        console.log(
          "🚀 ~ file: ScheduleInfo.vue ~ line 386 ~ newCourseTabledata=data.result.map ~ newCourseTabledata",
          newCourseTabledata
        );

        this.$emit("courseTableData", newCourseTabledata);
      } catch (err) {
        this.$message.error("没有排课");
        this.$emit("courseTableData", []);
        console.log(err);
      }
    },
  },
};
</script>

<style lang="scss">
div {
  /* 顶部选择框宽度 */
  --width: 20%;
}
.topSelect {
  display: flex;
  justify-content: space-around;
}
</style>
